//用户认证
package controllers

import (
	//	"encoding/json"
	"fmt"
	//	"gitee.com/lzqysoft/ilive/common"
	"gitee.com/lzqysoft/ilive/libs/jwtbeego"

	//	"gitee.com/lzqysoft/ilive/libs"
	"gitee.com/lzqysoft/ilive/models"
	"time"

	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/utils/captcha"

	"github.com/astaxie/beego"
)

type AuthController struct {
	CommonController
}

func (a *AuthController) Prepare() {
	a.EnableXSRF = false
}

func (c *AuthController) URLMapping() {
	c.Mapping("Login", c.Login)
	c.Mapping("Logout", c.Logout)
	c.Mapping("Loginyz", c.Loginyz)
	c.Mapping("Getcpt", c.Getcpt)
	c.Mapping("Vercpt", c.Vercpt)
	c.Mapping("Health", c.Health)
}

var cpt *captcha.Captcha

//var tokens cache.Cache

func init() {

	// use beego cache system store the captcha data
	store := cache.NewMemoryCache()
	//store := libs.InitCache()
	//	tokens = cache.NewMemoryCache()
	cpt = captcha.NewWithFilter("/captcha/", store)
}

// @Title 生成验证码
// @Description Getcpt
// @Success 200 {object} cpt
// @Failure 403 : worng
// @router /Getcpt [get]
func (c *AuthController) Getcpt() {
	cpt.StdHeight = 50
	cpt.StdWidth = 150
	cptId, _ := cpt.CreateCaptcha()
	url := fmt.Sprintf("%s%s.png", cpt.URLPrefix, cptId)
	jsond := make(map[string]interface{})
	jsond["cptId"] = cptId
	jsond["url"] = url
	c.Data["json"] = jsond
	c.ServeJSON()
}

// @Title 验证码验证
// @Description Vercpt
// @Param	captcha_id	  query	  string	true	"输入验证码"
// @Param	captcha	  query	  string	true	"验证码id"
// @Success 200 {object} cpt
// @Failure 403 : worng
// @router /Vercpt [post]
func (c *AuthController) Vercpt() {
	//	log.Debug("re is :", c.Ctx.Request)
	cptt := cpt.VerifyReq(c.Ctx.Request)
	jsond := make(map[string]interface{})
	jsond["cptt"] = cptt
	c.Data["json"] = jsond
	c.ServeJSON()

}

// @Title Health
// @Description 健康检查
// @Success 200 Ip
// @Failure 403 : worng
// @router /Health [get]
func (c *AuthController) Health() {
	//	log.Debug("re is :", c.Ctx.Request)
	var jd Jdata
	jd.Code = 0
	jd.Message = "ok"
	c.Data["json"] = jd
	c.ServeJSON()

}

// @Title 退出
// @Description User Login by username and pwd
// @Success 200
// @Failure 403
// @router /Logout [get]
func (this *AuthController) Logout() {
	this.DelSession("userinfo")
	this.Redirect("/", 302)
}

// @Title Login
// @Description User Login by username and pwd
// @Param	name	query	string	true	"admin"
// @Param	pwd	  query	  string	true	"admin"
// @Success 200 {object} models.User
// @Failure 403 :username or pwd was worng
// @router /Login [post]
func (c *AuthController) Login() {
	name := c.GetString("name")
	pswd := c.GetString("pwd")
	jdata := make(map[string]interface{})
	user, err := models.CheckLogin(name, pswd)
	if err == nil {
		userprof, _ := models.GetUserprofById(user.Id)
		tokenString := c.Ctx.Input.Header("Authorization")
		et := jwtbeego.EasyToken{
			Userid: user.Id,
			Orgid:  user.Organization.Id,
			Appid:  beego.AppConfig.String("appname"),
		}
		beego.Debug(et)
		beego.Debug(user.Id)
		jwt, ts, err := jwtbeego.Parse(tokenString)
		if err != nil {
			beego.Error(err)
			ts, err = et.GetToken()
			if err != nil {
				beego.Error(err)
				c.RetError(ErrToken)
			}
		} else if jwt.Userid != user.Id {
			beego.Debug(jwt.Userid, user.Id)
			ts, err = et.GetToken()
			if err != nil {
				c.RetError(ErrToken)
			}
		}
		org, _ := models.GetOrganizationById(user.Organization.Id)
		jdata["code"] = 0
		jdata["message"] = "登录成功！"
		jdata["token"] = ts
		jdata["userinfo"] = user
		jdata["userprof"] = userprof
		jdata["org"] = org
		c.Data["json"] = jdata
		userprof.Logincount = userprof.Logincount + 1
		userprof.Loginip = c.Ctx.Input.IP()
		userprof.Logintime = time.Now()
		models.UpdateUserprofById(userprof)
		//		c.Dlog("登录系统，用户名为：", user.Id, 2)

	} else {
		jdata["code"] = 1
		jdata["message"] = err.Error()
		c.Data["json"] = jdata

	}

	c.ServeJSON()
}

// @Title Login 验证码
// @Description User Login by username and pwd
// @Param	name	query	string	true	"admin"
// @Param	pwd	  query	  string	true	"admin"
// @Success 200 {object} models.User
// @Failure 403 :username or pwd was worng
// @router /Loginyz [post]
func (c *AuthController) Loginyz() {
	name := c.GetString("name")
	pswd := c.GetString("pwd")
	captcha := c.GetString("captcha")
	captchaid := c.GetString("captchaid")

	//	jsond := make(map[string]interface{})
	jdata := make(map[string]interface{})
	succe := false
	succe = cpt.Verify(captchaid, captcha)
	if succe {
		user, err := models.CheckLogin(name, pswd)
		if err == nil {
			//			role, _ := models.GetRoleByUserId(user.Id)
			//			orginfo, _ := models.GetOrganizationById(user.OrgId)
			//			accessList := GetResList(user.Id)
			userprof, _ := models.GetUserprofById(user.Id)
			tokenString := c.Ctx.Input.Header("Authorization")
			et := jwtbeego.EasyToken{
				Userid: user.Id,
				Orgid:  user.Organization.Id,
				Appid:  beego.AppConfig.String("appname"),
			}
			beego.Debug(et)
			beego.Debug(user.Id)
			jwt, ts, err := jwtbeego.Parse(tokenString)
			if err != nil {
				beego.Error(err)
				ts, err = et.GetToken()
				beego.Debug("errerr:", err)
				if err != nil {
					beego.Error(err)
					c.RetError(ErrToken)
				}
			} else if jwt.Userid != user.Id {
				beego.Debug(jwt.Userid, user.Id)
				ts, err = et.GetToken()
				if err != nil {
					c.RetError(ErrToken)
				}
			}

			jdata["code"] = 0
			jdata["message"] = "登录成功！"
			jdata["token"] = ts
			//			jsond["user"] = user
			//			jsond["role"] = role
			//			jsond["userprof"] = userprof
			//			jsond["org"] = orginfo
			//			jsond["accesslist"] = accessList
			//			jdata["data"] = jsond
			//			key := []byte(common.Substr(tokenString, 5, 16))
			//			juser, _ := json.Marshal(user)
			//			beego.Debug("juser:", juser)
			//			auser, _ := common.AesEncrypt(juser, key, key)
			//			jdata["aes"] = auser

			c.Data["json"] = jdata

			//			if Ssdbp.Client == nil {
			//				if er := Ssdbp.InitSsdb(); er != nil {
			//					jdata["code"] = 3
			//					jdata["message"] = er.Error()
			//					return
			//				}
			//			}
			//			_, e := Ssdbp.Client.Do("zset", "session", user.Id, time.Now().Unix())

			//			if e != nil {
			//				jdata["code"] = 4
			//				jdata["message"] = e.Error()
			//				log.Error("错误是：", time.Now().Unix(), e)
			//				c.Data["json"] = jdata
			//			}
			userprof.Logincount = userprof.Logincount + 1
			userprof.Loginip = c.Ctx.Input.IP()
			userprof.Logintime = time.Now()
			models.UpdateUserprofById(userprof)
			//			c.Dlog("登录系统，用户名为：", user.Id, 2)
			beego.Debug("errerr:", err)

		} else {
			jdata["code"] = 1
			jdata["message"] = err.Error()
			c.Data["json"] = jdata

		}
	} else {
		jdata["code"] = 2
		jdata["message"] = "验证码错误"
		c.Data["json"] = jdata
	}

	c.ServeJSON()
}
